#include "rs_socket.h"
#include <boost/thread.hpp>

network::rs_socket::rs_socket(const string &file)
{
	termios newtio;
	_fd = open(file.c_str(), O_RDWR | O_NOCTTY);
	if(_fd == -1) {
		throw network::socket_exception("Error, couldn't open" + file);
	}

	bzero(&newtio, sizeof(newtio));

	/*
	 * BAUDRATE = set bps
	 * CS8 = 8n1
	 * CLOCAL = local connection, no modem control
	 * CREAD = enable receiving characters
	 */
	newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
	newtio.c_cflag &= ~CRTSCTS;	 // disable hardware flow control
	/*
	 * IGNPAR = ignore bytes with parity errors
	 * ICRNL = map CR to NL
	 */
	newtio.c_iflag = IGNPAR | ICRNL;
	newtio.c_oflag = 0;
	/*
	 * ICANON = enable cononical input
	 */
	newtio.c_lflag = 0;

	/* 
	 * initialize all control characters 
	 * default values can be found in /usr/include/termios.h, and are given
	 * in the comments, but we don't need them here
	 */
	newtio.c_cc[VINTR]    = 0; /* Ctrl-c */ 
	newtio.c_cc[VQUIT]    = 0; /* Ctrl-\ */
	newtio.c_cc[VERASE]   = 0; /* del */
	newtio.c_cc[VKILL]    = 0; /* @ */
	newtio.c_cc[VEOF]     = 4; /* Ctrl-d */
	newtio.c_cc[VTIME]    = 0; /* inter-character timer unused */
	newtio.c_cc[VMIN]     = 1; /* blocking read until 1 character arrives */
	newtio.c_cc[VSWTC]    = 0; /* '\0' */
	newtio.c_cc[VSTART]   = 0; /* Ctrl-q */ 
	newtio.c_cc[VSTOP]    = 0; /* Ctrl-s */
	newtio.c_cc[VSUSP]    = 0; /* Ctrl-z */
	newtio.c_cc[VEOL]     = 0; /* '\0' */
	newtio.c_cc[VREPRINT] = 0; /* Ctrl-r */
	newtio.c_cc[VDISCARD] = 0; /* Ctrl-u */
	newtio.c_cc[VWERASE]  = 0; /* Ctrl-w */
	newtio.c_cc[VLNEXT]   = 0; /* Ctrl-v */
	newtio.c_cc[VEOL2]    = 0; /* '\0' */
	
	/*
	 * clean modem line
	 */
	tcflush(_fd, TCIFLUSH);
	tcsetattr(_fd, TCSANOW, &newtio);
}

network::rs_socket::~rs_socket()
{
}

void network::rs_socket::send(const string &str)
{
	write(_fd, str.c_str(), str.size());
}

string network::rs_socket::recv()
{
	char buf[100];
	int res = read(_fd, buf, 100);
	buf[res] = 0;
	string str(buf);
	return str;
}

